package com.jiaquyun.jcyx.app

import android.content.Context
import androidx.multidex.MultiDex
import androidx.room.Room
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.SPStaticUtils
import com.jiaquyun.jcyx.BuildConfig
import com.jiaquyun.jcyx.db.AppDatabase
import com.jiaquyun.jcyx.entity.UserIndex
import com.jiaquyun.jcyx.entity.UserInfo
import com.jiaquyun.jcyx.entity.UserShops
import com.module.lemlin.http.HttpServiceFactory
import com.module.lemlin.owner.OwnerApplication
import rxhttp.RxHttp
import rxhttp.RxHttpPlugins
import rxhttp.wrapper.utils.LogUtil
import java.lang.Exception

class JCApplication : OwnerApplication() {

    companion object {
        private const val DB_NAME = "JiaQuYunClient.db"
        private const val KEY_HTTP_TOKEN = "token"

        lateinit var appDatabase: AppDatabase

        val token: String
            get() = SPStaticUtils.getString(AppConstance.SPS_KEY_TOKEN)

        val userInfo: UserInfo?
            get() = try {
                GsonUtils.fromJson(
                    SPStaticUtils.getString(AppConstance.SPS_KEY_USER_INFO),
                    UserInfo::class.java
                )
            } catch (e: Exception) {
                null
            }

        val userIndex: UserIndex?
            get() = try {
                GsonUtils.fromJson(
                    SPStaticUtils.getString(AppConstance.SPS_KEY_USER_INDEX),
                    UserIndex::class.java
                )
            } catch (e: Exception) {
                null
            }

        val userShops: UserShops?
            get() = try {
                GsonUtils.fromJson(
                    SPStaticUtils.getString(AppConstance.SPS_KEY_USER_SHOPS),
                    UserShops::class.java
                )
            } catch (e: Exception) {
                null
            }
    }

    override fun attachBaseContext(base: Context?) {
        super.attachBaseContext(base)
        //初始dex
        MultiDex.install(base)
    }

    override fun onCreate() {
        super.onCreate()
        //初始数据库
        appDatabase = Room.databaseBuilder(
            application, AppDatabase::class.java, DB_NAME
        )
            .allowMainThreadQueries()
            .build()

        RxHttpPlugins.init(HttpServiceFactory.client().build())
            .setDebug(BuildConfig.DEBUG)
            .setOnParamAssembly { it.addHeader(KEY_HTTP_TOKEN, token) }
    }

}